package com.lujianfei.mqtt.login

import android.content.Intent
import android.view.WindowManager
import androidx.activity.viewModels
import androidx.core.view.isVisible
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.lujianfei.mqtt.BaseActivity
import com.lujianfei.mqtt.MainActivity
import com.lujianfei.mqtt.R
import com.lujianfei.mqtt.common.KVSpUtils
import com.lujianfei.mqtt.databinding.ActivityLoginBinding
import com.lujianfei.mqtt.ktx.toJsonString
import com.lujianfei.mqtt.net.config.USER_ACCOUNT
import com.wn.common.ktx.dismissKeyBoard
import dagger.hilt.android.AndroidEntryPoint

/**
 * @Author: wn
 * @Date: 2024/4/16 10:21
 * @Description: 登陆页面
 */
@AndroidEntryPoint
class LoginActivity : BaseActivity<ActivityLoginBinding>() {
  override fun getLayoutRes() = R.layout.activity_login

  private val loginViewModel by viewModels<LoginViewModel>()

  override fun initView() {
    super.initView()
    mBinding.apply {
      vm = loginViewModel
      // region 默认不弹出软件盘
      textAccount.apply {
        requestFocus()
        isFocusableInTouchMode = true
      }
      textPass.apply {
        requestFocus()
        isFocusableInTouchMode = true
      }
      window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
      // endregion
    }
  }

  override fun initData() {
    super.initData()
    loginViewModel.apply {
      userInfo.observeKt {
        if (it == null) return@observeKt
        it.apply {
          // 跳转主页面
          ToastUtils.showLong("当前登陆的账号是：${it.account}")
          // data class --> string
          val str = it.toJsonString()
          // MMKV 存储一下
          KVSpUtils.put(USER_ACCOUNT,str)
          Intent(this@LoginActivity, MainActivity::class.java).apply {
            startActivity(this)
          }
          // 关闭 Activity
          finish()
        }
      }
      // 加载进度条显示
      isLoading.observeKt {
        if (it == null) return@observeKt
        mBinding.pbLogin.isVisible = it
      }
    }
  }
}